<template>
    <div>
        <div class="step-wrap">
            <el-steps :space="200" :active="active" finish-status="success" align-center v-if="form.isPublish === '0'">
                <el-step title="创建MR"></el-step>
                <el-step title="合并代码"></el-step>
                <el-step title="打测试tag"></el-step>
            </el-steps>
            <el-steps :space="200" :active="active" finish-status="success" align-center v-else>
                <el-step title="合并master"></el-step>
                <el-step title="创建MR"></el-step>
                <el-step title="合并代码"></el-step>
                <el-step title="打测试tag"></el-step>
            </el-steps>
        </div>
        <div class="form-wrap">
            <el-form ref="form" :model="form" :rules="rules" label-width="150px">
                <el-form-item label="工程" prop="project">
                    <el-select v-model="form.project">
                        <el-option v-for="item in projectsOptions" :key="item.value" :value="item.value" :label="item.label">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="版本号" prop="version">
                    <el-select v-model="form.version">
                        <el-option v-for="item in branchsOptions" :key="item.value" :value="item.value" :label="item.label">
                        </el-option>
                    </el-select>
                </el-form-item>
                 <el-form-item label="是否多版本测试" prop="isTestSet" v-if="form.project==148">
                    <el-radio v-model="form.isTestSet" label="1">是</el-radio>
                    <!-- <el-radio v-model="form.isTestSet" label="0">否</el-radio> -->
                </el-form-item>
                <el-form-item label="多版本号" prop="testSetVersion" v-if="form.isTestSet=='1'&&form.project==148">
                    <el-select v-model="form.testSetVersion">
                        <el-option v-for="item in testSetList" :key="item.value" :value="item.value" :label="item.label">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="textName" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="有版本发布" prop="isPublish">
                    <el-radio v-model="form.isPublish" label="1">是</el-radio>
                    <el-radio v-model="form.isPublish" label="0">否</el-radio>
                </el-form-item>
                <el-form-item label="上一次发布的版本号" prop="prePublishVersion" v-if="this.form.isPublish !== '1'">
                    <el-select v-model="form.prePublishVersion">
                        <el-option v-for="item in branchsOptions" :key="item.value" :value="item.value" :label="item.label">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="合并到master的分支" prop="preMergeVersion" v-if="this.form.isPublish !== '1'">
                    {{ preMergeVersion }}
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onPubilshTest" :loading="isLoading">打包测试版</el-button>
                    <!-- 在打包正式版的时候不能合并master，合并master操作一定是在打包测试版的时候进行的 -->
                    <!-- <el-tooltip class="item" effect="dark" placement="right">
                        <div slot="content" style="line-height: 22px">
                            <p>发布分支是在最大的测试分支号的基础上打tag，如果不是请手动处理</p>
                            <p>例如：当前分支有多个测试tag</p>
                            <p>hotfix_1.0.0.0_1, hotfix_1.0.0.0_2, hotfix_1.0.0.0_3</p>
                            <p>我们是根据hotfix_1.0.0.0_3打发布的tag，如果不是请手动处理</p>
                        </div> -->
                    <el-button v-if="this.form.isPublish === '1'" disabled>打包正式版</el-button>
                    <el-button type="primary" @click="onShowChecklist" v-else>打包正式版</el-button>
                    <!-- </el-tooltip> -->
                </el-form-item>
            </el-form>
            <div v-if="testBranchName" style="margin-top: 20px; color: red; font-weight: 700">
                测试分支：{{ testBranchName }}
            </div>
             <div v-if="bossBranchName" style="margin-top: 20px; color: red; font-weight: 700">
                BOSS测试分支：{{ bossBranchName }}
            </div>
            <div v-if="publishBranchName" style="margin-top: 20px; color: red; font-weight: 700">
                正式分支：{{ publishBranchName }}
            </div>
        </div>
        <el-dialog title="发布checklist" :visible.sync="checklistVisible" center>
            <el-checkbox-group v-model="checklist">
                <el-checkbox v-for="item in checklistOptions" :key="item.value" :label="item.value" style="color: red">{{ item.label }}</el-checkbox>
            </el-checkbox-group>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="onPublish" :loading="isPublishLoading">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import {
    findProjects, findBranchsByProject,
    createMergeRequest, acceptMergeRequest,
    findTagsByProject, createTagByProject,
    closeMergeRequest, removeTagByProject, findMergeRequest, findMergeRequestList } from './api/index.js'
export default {
    name: 'publish',
    data () {
        return {
            form: {
                version: '',
                project: '',
                isPublish: '1', // 是否之前有版本发布
                testSetVersion: 'development_TestSet',
                isTestSet: '1',
                prePublishVersion: ''
            },
            preMergeVersion: '',
            projectsOptions: [],
            branchsOptions: [],
            branchs: [],
            isLoading: false,
            isPublishLoading: false,
            active: 0,
            rules: {
                project: [
                    { required: true, message: '此项为必填项！' }
                ],
                version: [
                    { required: true, message: '此项为必填项！' }
                ],
                isPublish: [
                    { required: true, message: '此项为必填项！' }
                ],
                isTestSet: [
                    { required: true, message: '此项为必填项！' }
                ],
                testSetVersion: [
                    { required: true, message: '此项为必填项！' }
                ],
                prePublishVersion: [
                    { required: true, message: '此项为必填项！' }
                ]
            },
            testBranchName: '',
            publishBranchName: '',
            bossBranchName: '',
            checklistVisible: false,
            checklist: [],
            checklistOptions: [
                { label: '请求前缀配置确认（api文件夹下面，config.js文件中production配置）', value: '1' },
                { label: 'Master分支已经合并到当前版本', value: '2' }
            ],
            textName: '',
            textList: '',
            testSetList: []
        }
    },
    computed: {
        // versionNum () {
        //     if (this.form.project === 148 && this.form.isTestSet === '1') {
        //         return this.form.testSetVersion.split('_')[1]
        //     } else {
        //         return this.form.version.split('_')[1]
        //     }
        // }
        versionNum () {
            return this.form.version.split('_')[1]
        }
    },
    watch: {
        'form.project' (val) {
            this.form.version = ''
            this.active = 0
            this.testBranchName = ''
            this.getBranchs(val)
        },
        'form.version' (val) {
            const textList = val.split('_')
            if (textList[2]) {
                this.textName = textList[2]
            } else {
                this.textName = '备注未写请确认'
            }

            this.active = 0
            this.testBranchName = ''
            this.publishBranchName = ''
        },
        async 'form.isPublish' (val) {
            this.active = 0
            this.testBranchName = ''
            this.publishBranchName = ''
            if (val != '1') {
                const { data: mergeInfo } = await findMergeRequestList({
                    projectId: this.form.project,
                    target_branch: 'master'
                })
                this.preMergeVersion = mergeInfo[0].source_branch
            }
        }
    },
    methods: {
        async getProjects () {
            const { data } = await findProjects()
            this.projectsOptions = data.map(item => ({
                label: item.name,
                value: item.id
            }))
        },
        async getBranchs (projectId) {
            const { data } = await findBranchsByProject({
                projectId
            })
            this.branchs = data
            this.branchsOptions = data.filter(item => item.name.indexOf('feature') !== -1).map(item => {
                const nameArr = item.name.split('_')
                if (nameArr.length < 2) {
                    return null
                }
                return {
                    label: nameArr[1],
                    value: item.name
                }
            })
            // TODO boss端 多版本发布 手动选中 development 一个 测试合合集
            this.testSetList = data.filter(item => item.name.indexOf('development') !== -1).filter(item => {
                const nameArr = item.name.split('_')
                return nameArr[1] && nameArr[1].toLowerCase().indexOf('testset') === 0
                // if (nameArr[1] && nameArr[1].toLowerCase().indexOf('testset') === 0) {
                //     console.log(item, nameArr)
                //     return {
                //         label: nameArr[1],
                //         value: item.name
                //     }
                // }
            }).map(item => {
                const nameArr = item.name.split('_')
                if (nameArr.length < 2) {
                    return null
                }
                return {
                    label: nameArr[1],
                    value: item.name
                }
            })
        },
        onShowChecklist () {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    this.checklistVisible = true
                    this.checklist = []
                }
            })
        },
        async onPublish () {
            this.isPublishLoading = true
            this.active = 0
            this.publishBranchName = ''
            try {
                // 1. 确认checklist
                if (this.checklist.length !== this.checklistOptions.length) {
                    this.$message.error('请确认完成checklist！')
                    this.isPublishLoading = false
                    return
                }
                // 确认最近发布版本和master是否一致
                const { data: mrgInfo } = await createMergeRequest({
                    projectId: this.form.project,
                    source_branch: this.form.prePublishVersion,
                    target_branch: 'master',
                    title: 'merge request ' + this.form.prePublishVersion,
                    description: `发布之前校验，master和上次发布版本是否一致`
                })
                if (mrgInfo.changes_count) {
                    this.isPublishLoading = false
                    this.checklistVisible = false
                    await closeMergeRequest({
                        projectId: this.form.project,
                        mrId: mrgInfo.iid
                    })
                    this.$message.error('上次发布的版本没有合并')
                    return
                } else {
                    this.isPublishLoading = false
                    this.checklistVisible = false
                    await closeMergeRequest({
                        projectId: this.form.project,
                        mrId: mrgInfo.iid
                    })
                }
                // 2. 打tag
                const { data: tags } = await findTagsByProject({
                    projectId: this.form.project
                })
                let maxTagNum = this.maxHotfixTag(tags)
                if (maxTagNum === 0) {
                    this.$message.error('尚未发布过测试版！请在测试版确认通过后发布！')
                    this.isPublishLoading = false
                    this.checklistVisible = false
                    return
                }
                // 已经发布过的tag，获取最大的后缀
                let lastIndex = this.versionNum.lastIndexOf('.')
                lastIndex = lastIndex !== -1 ? lastIndex : this.versionNum.length
                const publishTagsNum = tags.filter(item => item.name.indexOf(this.versionNum.substring(0, lastIndex)) === 0).map(item => item.name.substring(lastIndex + 1))
                // eslint-disable-next-line
                let maxPublishTagNum = -1
                if (publishTagsNum.length > 0) {
                    maxPublishTagNum = Math.max.apply(Math, publishTagsNum)
                }
                await createTagByProject({
                    projectId: this.form.project,
                    tag_name: this.versionNum.substring(0, lastIndex) + '.' + (maxPublishTagNum * 1 + 1),
                    ref: 'hotfix_' + this.versionNum + '_' + maxTagNum
                })
                this.publishBranchName = this.versionNum.substring(0, lastIndex) + '.' + (maxPublishTagNum * 1 + 1)
                // 考虑第四位  习惯_数字标记
                // this.publishBranchName = this.versionNum + '_' + (maxTagNum * 1 + 1)
                this.isPublishLoading = false
                this.checklistVisible = false
            } catch (e) {
                this.isPublishLoading = false
            }
        },
        onPubilshTest () {
            this.isLoading = true
            this.active = 0
            this.testBranchName = ''
            this.$refs.form.validate(async (valid) => {
                if (valid) {
                    try {
                        if (this.form.isPublish === '1') {
                            // 1. 最近有发布的情况下，检查master是否合并到了对应的feature分支
                            const { data: masterMerge } = await createMergeRequest({
                                projectId: this.form.project,
                                source_branch: 'master',
                                target_branch: this.form.version,
                                title: 'merge request from master',
                                description: `merge from master to ${this.form.version}`
                            })
                            if (masterMerge.changes_count) {
                                await acceptMergeRequest({
                                    projectId: this.form.project,
                                    mrId: masterMerge.iid
                                })
                            } else {
                                await closeMergeRequest({
                                    projectId: this.form.project,
                                    mrId: masterMerge.iid
                                })
                            }
                            this.active++
                        }
                        // 2. 建merge request
                        // 合过master 直接打包
                        // TODO boss 多版本 获取 目标 development 分支号 Testset
                        const targetBranch = this.branchs.filter(item => item.name.indexOf('development_' + this.versionNum) === 0)
                        if (targetBranch.length > 1) {
                            this.$message.error('匹配的development分支过多：' + targetBranch.length)
                            this.isLoading = false
                        } else if (targetBranch.length === 0) {
                            this.$message.error('没有找到对应的development分支！')
                            this.isLoading = false
                        } else {
                            // merge request的title都会加上版本号，这里先查询有当前版本号的merge request，如果存在就不用创建merge request
                            // merge request的命名规则：必须加版本号
                            const { data: mergeRequests } = await findMergeRequest({
                                projectId: this.form.project,
                                search: this.versionNum
                            })
                            let mergeId = ''
                            if (mergeRequests.length <= 0) {
                                // 如果merge request不遵守规则，这边还是会出现冲突的情况
                                // 冲突手动去gitlab 修复
                                // feature 合并到 development
                                const { data: mrInfo } = await createMergeRequest({
                                    projectId: this.form.project,
                                    source_branch: this.form.version,
                                    target_branch: targetBranch[0].name,
                                    title: 'merge request ' + this.versionNum,
                                    description: `merge from ${this.form.version} to ${targetBranch[0].name}`
                                })
                                mergeId = mrInfo.iid
                                // 如果当前feature分支和development分支没有区别，就关闭这个merge request
                                // 这样操作的原因是，gitlab一直没有提供接口判断两个分支有没有差别，3年了一直没给，这效率没谁了
                                if (!mrInfo.changes_count) {
                                    this.$message.warning('当前分支没有更新！')
                                    await closeMergeRequest({
                                        projectId: this.form.project,
                                        mrId: mrInfo.iid
                                    })
                                    this.isLoading = false
                                    return
                                }
                                this.active++
                            } else {
                                mergeId = mergeRequests[0].iid
                                this.active++
                            }
                            // 3. 合并操作
                            await acceptMergeRequest({
                                projectId: this.form.project,
                                mrId: mergeId
                            })
                            this.active++
                            // 4. 打tag
                            const { data: tags } = await findTagsByProject({
                                projectId: this.form.project
                            })
                            let maxTagNum = this.maxHotfixTag(tags)
                            console.log(maxTagNum)
                            await createTagByProject({
                                projectId: this.form.project,
                                tag_name: 'hotfix_' + this.versionNum + '_' + (maxTagNum * 1 + 1),
                                ref: targetBranch[0].name
                            })
                            this.active++
                            this.isLoading = false
                            this.testBranchName = 'hotfix_' + this.versionNum + '_' + (maxTagNum * 1 + 1)
                            // 5. 删除以前的tag，保留两个版本，多余的tag删除掉
                            if (maxTagNum - 1 > 0) {
                                // 判断要删除的tag是否存在
                                const delTag = tags.filter(item => item.name === 'hotfix_' + this.versionNum + '_' + (maxTagNum - 1))
                                if (delTag.length > 0) {
                                    await removeTagByProject({
                                        projectId: this.form.project,
                                        tagName: 'hotfix_' + this.versionNum + '_' + (maxTagNum - 1)
                                    })
                                }
                            }
                            // TODO boss 项目 无需hotfix 直接 可以 feature => development=>developmrnt_Testset
                            // testSetVersion developmrnt_Testset 分支
                            var mergenId = ''
                            if (this.form.project === 148 && this.form.isTestSet === '1') {
                                const testSetVersion = this.form.testSetVersion
                                const { data: mrgInfo } = await createMergeRequest({
                                    projectId: this.form.project,
                                    source_branch: targetBranch[0].name,
                                    target_branch: testSetVersion,
                                    title: 'merge request ' + this.versionNum,
                                    description: `merge from ${targetBranch[0].name} to ${testSetVersion}`
                                })
                                mergenId = mrgInfo.iid
                                // 如果当前feature分支和development分支没有区别，就关闭这个merge request
                                // 这样操作的原因是，gitlab一直没有提供接口判断两个分支有没有差别，3年了一直没给，这效率没谁了
                                if (!mrgInfo.changes_count) {
                                    this.$message.warning('当前分支和develop_Test没有更新！')
                                    await closeMergeRequest({
                                        projectId: this.form.project,
                                        mrId: mrgInfo.iid
                                    })
                                    this.isLoading = false
                                    return
                                }
                                await acceptMergeRequest({
                                    projectId: this.form.project,
                                    mrId: mergenId
                                })
                            }
                            // TODO 打完正常tags BOSS 端 再继续 development = 》development_Testset
                            if (this.form.project === 148 && this.form.isTestSet === '1') {
                                this.bossBranchName = this.form.testSetVersion
                            } else {
                                this.bossBranchName = ''
                            }
                        }
                    } catch (e) {
                        this.isLoading = false
                    }
                } else {
                    this.isLoading = false
                }
            })
        },
        maxHotfixTag (tags) {
            const versionTagsNum = tags.filter(item => item.name.indexOf('hotfix_' + this.versionNum + '_') !== -1).map(item => item.name.replace('hotfix_' + this.versionNum + '_', ''))
            let maxTagNum = 0
            if (versionTagsNum.length > 0) {
                maxTagNum = Math.max.apply(Math, versionTagsNum)
            }
            return maxTagNum
        }
    },
    mounted () {
        this.getProjects()
        // jsonp(`http://192.168.20.241:7080/job/web-B2b-prod/lastSuccessfulBuild/api/json?token=1114f6a1d0bbc8a6fcff69efdde884a5c5`, null, (err, data) => {
        //     console.log(err)
        //     console.log(data)
        // })
        // const { data } = axios.get(`http://192.168.20.249:7080/job/another-web-crm-test/lastSuccessfulBuild/api/json?user=zhangjie:11fb901ce8b988291314e6e5bd0c23b8c4&token=11fb901ce8b988291314e6e5bd0c23b8c4`, {
        //     'headers': { 'token': '11fb901ce8b988291314e6e5bd0c23b8c4' }
        // })
        // console.log(data)
    }
}
</script>

<style lang="scss" scoped>
.el-checkbox + .el-checkbox {
    margin-top: 20px;
    margin-left: 0;
}
.el-checkbox {
    display: block;
}
.step-wrap {
    margin-bottom: 30px;
    padding: 10px;
}
/deep/ .el-checkbox,
.el-checkbox__input {
    white-space: normal;
    word-break: break-all;
}
/deep/ .el-checkbox__label {
    display: inline;
}
</style>
